package com.pj.project4sp.sp_mqqt_log;

public class SnowflakeIdGenerator {
    // 起始的时间戳
    private final static long START_STAMP = 1480166465631L;

    // 每一部分占用的位数
    private final static long SEQUENCE_BIT = 12; // 序列号占用的位数
    private final static long MACHINE_BIT = 5; // 机器标识占用的位数
    private final static long DATACENTER_BIT = 5; // 数据中心占用的位数

    // 每一部分的最大值
    private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);

    // 每一部分向左的位移
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    private static long datacenterId = 1; // 数据中心标识
    private static long machineId = 1; // 机器标识
    private static long sequence = 0L; // 序列号
    private static long lastStamp = -1L; // 上一次时间戳

    public SnowflakeIdGenerator() {
        // 默认构造器
    }

    public static synchronized long nextId() {
        long currStamp = getNewStamp();
        if (currStamp < lastStamp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStamp == lastStamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                // 当前毫秒内的序列号已经使用完，等待下一毫秒
                currStamp = getNextMillis();
            }
        } else {
            sequence = 0L;
        }

        lastStamp = currStamp;

        return (currStamp - START_STAMP) << TIMESTAMP_LEFT
                | datacenterId << DATACENTER_LEFT
                | machineId << MACHINE_LEFT
                | sequence;
    }

    private static long getNewStamp() {
        return System.currentTimeMillis();
    }

    private static long getNextMillis() {
        long timestamp = getNewStamp();
        while (timestamp <= lastStamp) {
            timestamp = getNewStamp();
        }
        return timestamp;
    }

}
